package com.h3c.nem.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.h3c.nem.async.AsyncSendMessage;
import com.h3c.nem.async.AsyncSyncDataToHRSS;
import com.h3c.nem.client.AbilityClient;
import com.h3c.nem.config.properties.EmailSendProperties;
import com.h3c.nem.entity.SdEmailTemplate;
import com.h3c.nem.entity.SdNoticeRecord;
import com.h3c.nem.entity.TbOfferWorker;
import com.h3c.nem.mapper.TbOfferStudyMapper;
import com.h3c.nem.mapper.TbSchoolMapper;
import com.h3c.nem.mapper.TbWorkerExperienceMapper;
import com.h3c.nem.sap.RfcManager;
import com.h3c.nem.service.*;
import com.h3c.nem.utils.EncryptionUtil;
import com.h3c.nem.vo.PtEsignRecordInfoVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Service
public class TestService {

    @Resource
    private ITbApprovalRecordService approvalRecordService;

    @Resource
    private ITbPersonnelRegisterMiddleService personnelRegisterMiddleService;

    @Resource
    private ITbOfferAttachmentService attachmentService;

    @Resource
    private ITbOfferFamilyService familyService;

    @Resource
    private ITbOfferStudyService studyService;

    @Resource
    private ITbWorkerExperienceService iTbWorkerExperienceService;
    @Resource
    private ITbOfferLanguageService iTbOfferLanguageService;
    @Resource
    private ITbWorkerExperienceService workerExperienceService;
    @Resource
    private ITbOfferPatentService iTbOfferPatentService;
    @Resource
    private ITbOfferModifyService iTbOfferModifyService;
    @Resource
    private ITbOfferArchieveService iTbOfferArchieveService;
    @Resource
    private ISdTodoTaskService iSdTodoTaskService;
    @Resource
    private ISdNoticeRecordService iSdNoticeRecordService;
    @Resource
    private ISdDeptService iSdDeptService;
    @Resource
    private TbSchoolMapper tbSchoolMapper;
    @Resource
    private AsyncSendMessage asyncSendMessage;
    @Resource
    private CommService commService;
    @Resource
    private TbWorkerExperienceMapper tbWorkerExperienceMapper;
    @Resource
    private ITbOfferContactorService contactorService;
    @Resource
    private ISdAllWorkerService iSdAllWorkerService;
    @Resource
    private ISdEmailTemplateService emailTemplateService;
    @Resource
    private ITbOfferWorkerService iTbOfferWorkerService;
    @Resource
    private BeiSenService beiSenService;
    @Resource
    AsyncSyncDataToHRSS asyncSyncDataToHRSS;

    @Resource
    private TbOfferStudyMapper tbOfferStudyMapper;
    @Resource
    private EmailSendProperties emailSendProperties;
    @Resource
    private ITbWorkerService iTbWorkerService;
    @Resource
    private ThreadPoolService threadPoolService;

    @Resource
    private AbilityClient abilityClient;
    @Resource
    private RfcManager rfcManager;

    @Value("${admp.url}")
    private String admpUrl;

    @Value("${ptability.token}")
    private String ptToken;

    @Value("${hrss.nem.account}")
    private String appId;

    @Value("${hrss.nem.password}")
    private String curSecret;

    private final SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");


    public void sendEmail(TbOfferWorker offerWorker, String samAccount, String emailAddress, String userPwd, String contactorName){
        String regularWorkerId = offerWorker.getRegularWorkerId();
        String workerId = offerWorker.getWorkerId();
        SdEmailTemplate template = emailTemplateService.getById("ELECTRONIC_SIGNATURE_DOCUMENT");
        String templateContent = template.getEmailTemplateContent();
        String templateTitle = template.getEmailTemplateTitle();

        // 判断员工类型，并添加不同邮件内容
        List<PtEsignRecordInfoVO> tbOfferRecord = abilityClient.getTbOfferRecord(offerWorker.getWorkerId(), 1);
        if (tbOfferRecord != null) {
            int index = 1;
            for (PtEsignRecordInfoVO vo : tbOfferRecord) {
                if (vo.getSfsId() != null) {
                    String id = vo.getSfsId();
                    String fileName = vo.getTemplateName();
                    String originalAddress ="http://api.eos-ts.h3c.com/ptability-manage/v1.0/ptUploadFile/downloadFileEncryption?fileId={}";
                    originalAddress = StrUtil.format(originalAddress, EncryptionUtil.getEncryptDataAES(id));
                    String inputMessage =  "<p>" + index + " " + fileName + "下载链接为" + originalAddress + "<br></p>";
                    templateContent += inputMessage;
                    index++;
                }
            }
            //短信
            SdNoticeRecord smsRecord = iSdNoticeRecordService.createSmsNoticeRecord(workerId, offerWorker.getWorkerName(),
                    offerWorker.getPhoneNo(), templateTitle, templateContent);
            asyncSendMessage.sendMessage(Collections.singletonList(smsRecord));
            //邮件
            SdNoticeRecord emailRecord = iSdNoticeRecordService.createEmailNoticeRecord("-1", workerId, offerWorker.getWorkerName(),
                    emailAddress, templateTitle, templateContent, "");
            asyncSendMessage.sendMessage(emailRecord, null);
        }



    }


    public void sendEmailAndSms(TbOfferWorker offerWorker, String samAccount, String emailAddress, String userPwd, String contactorName) {
        sendEmail(offerWorker, samAccount, emailAddress, userPwd, contactorName);
        String regularWorkerId = offerWorker.getRegularWorkerId();
        String workerId = offerWorker.getWorkerId();
        //发送短信和邮件给预备员工
        SdEmailTemplate template = emailTemplateService.getById("GEN_ACCOUNT_DOMAIN_TEMPLATE");
        String templateContent = template.getEmailTemplateContent();
        String templateTitle = template.getEmailTemplateTitle();
        templateContent = templateContent.replace("{正式工号}", regularWorkerId)
                .replace("{域账号}", samAccount)
                .replace("{公司邮箱}", emailAddress)
                .replace("{初始密码}", userPwd)
                .replace("{直接主管}", offerWorker.getDirectManager())
                .replace("{部门接口人}", contactorName);
        templateContent += "<p>您好，您签署的如下入职文件已经审核通过：<br></p>";
        // 判断员工类型，并添加不同邮件内容


        SdNoticeRecord smsRecord = iSdNoticeRecordService.createSmsNoticeRecord(workerId, offerWorker.getWorkerName(),
                offerWorker.getPhoneNo(), templateTitle, templateContent);
        asyncSendMessage.sendMessage(Collections.singletonList(smsRecord));
        //邮件
        SdNoticeRecord emailRecord = iSdNoticeRecordService.createEmailNoticeRecord("-1", workerId, offerWorker.getWorkerName(),
                emailAddress, templateTitle, templateContent, "");
        List<File> fileList = getEsignFileList(workerId);
        asyncSendMessage.sendMessage(emailRecord, fileList);
    }

    public List<File> getEsignFileList(String workerId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("workerId", workerId);
        jsonObject.put("sceneType", "1");
        JSONObject result = abilityClient.esignRecord(jsonObject, ptToken);
        String status = result.getString("status");
        if (Objects.equals(status, "200")) {
            Object data = result.get("data");
            List<String> sfsIdList = (List<String>) data;
            List<File> fileRes = new ArrayList<>();
            for (String sfsId : sfsIdList) {
                JSONObject fileResult = abilityClient.downloadFile(sfsId, "合同.pdf", "f23104");
                String fileBase64 = fileResult.getJSONObject("data").getString("file");
                String fileName = fileResult.getJSONObject("data").getString("filename");
                File temp = FileUtil.writeBytes(Base64.decode(fileBase64), "download/" + fileName + ".pdf");
                fileRes.add(temp);
            }
            return fileRes;
        }
        return null;
    }

}

